import Vue from 'vue'
import Vuex from 'vuex'
import {getlyric,getSearch,findMessage} from './api.js'
import { Indicator } from 'mint-ui';

Vue.use(Vuex);

var state={
    lyric:[],
    test:'',
    musicList:[],
    searchmusic: localStorage.music ? JSON.parse(localStorage.music) : [],
    searchShow:true,
    play:false
}
const actions={
    findlyric({commit},id){
        let p = getlyric(id);
        p.then((resp) => {
            commit("findlyric", resp.data.lrc.lyric);
        });
        p.catch((err)=>{
            console.log(err);
        });
    },
    findmusic({commit},txt){
        Indicator.open('加载中...');
        let p = getSearch(txt);
        p.then((resp)=>{
            Indicator.close();
            commit("findmusic", resp.data.result.songs);
        });
        p.catch((err)=>{
            Indicator.close();
            console.log(err);
        });
    },
    getplay({commit},type){
        commit('getplay',type);
    },
    getMessage({commit}){
        commit('getMessage');
    }
}
const mutations={
    findlyric:(state,data)=>{
        var arr=data.split("\n");
        var nowLyric=[{'txt':'','time':0,'select':false}]
        state.lyric=[];
        for(let i=0;i<arr.length-1;i++){
            let obj1={};
            obj1.txt=arr[i];
            obj1.time=parseInt(arr[i].slice(1,3))*60+parseInt(arr[i].slice(4,6));
            obj1.select=false;
            nowLyric.push(obj1);
        }
        var obj2={'txt':'','time':9999,'select':false};
        nowLyric.push(obj2);
        state.lyric=nowLyric;
        console.log(JSON.stringify(state.lyric));
    },
    findmusic:(state,data)=>{
        state.musicList=data;
    },
    addsearchmusic:(state,txt)=>{
        var repeat=false;
        for(let i=0;i<state.searchmusic.length;i++){
            if(state.searchmusic[i]==txt){
                repeat=true;
            }
        }
        if(!repeat){
            state.searchmusic.unshift(txt);
        }
        if(state.searchmusic.length>5){
            state.searchmusic=state.searchmusic.slice(0,5);
        }
        localStorage.music=JSON.stringify(state.searchmusic);
    },
    getplay:(state,type)=>{
        state.play=type;
    },
    getMessage:(state)=>{
        var p = findMessage();
        // p.then((res)=>{
        //   state.name=response.data.songs[0].name;
        //   state.auther=response.data.songs[0].artists[0].name;
        //   state.imgPath=response.data.songs[0].album.picUrl;
        //   state.mp3Url=response.data.songs[0].mp3Url
        //     console.log(res.data);
        // });
    }
}

export const store=new Vuex.Store({
    state,
    mutations,
    actions
});